<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="Java NIO之Selector（选择器） 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;snailclimb&#x2F;p&#x2F;9086334.html  一 Selector（选择器）介绍Selector 一般称 为选择器 ，当然你也可以翻译为 多路复用器 。它是Java NIO核心组件中的一个，用于检查一个或多个NIO Channel（通道）的状态是否处于可读、可写。如此可以实现单线程管理多个c">
<meta property="og:type" content="article">
<meta property="og:title" content="Java NIO之Selector（选择器）">
<meta property="og:url" content="http://littlefxc.github.io/2021/05/28/Java%20NIO%E4%B9%8BSelector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8)/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="Java NIO之Selector（选择器） 转载自https:&#x2F;&#x2F;www.cnblogs.com&#x2F;snailclimb&#x2F;p&#x2F;9086334.html  一 Selector（选择器）介绍Selector 一般称 为选择器 ，当然你也可以翻译为 多路复用器 。它是Java NIO核心组件中的一个，用于检查一个或多个NIO Channel（通道）的状态是否处于可读、可写。如此可以实现单线程管理多个c">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-05-28T11:39:32.000Z">
<meta property="article:modified_time" content="2021-05-28T01:08:06.500Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="netty">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://littlefxc.github.io/2021/05/28/Java%20NIO%E4%B9%8BSelector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8)/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>Java NIO之Selector（选择器） | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Java-NIO%E4%B9%8BSelector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8%EF%BC%89"><span class="nav-text">Java NIO之Selector（选择器）</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%80-Selector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8%EF%BC%89%E4%BB%8B%E7%BB%8D"><span class="nav-text">一 Selector（选择器）介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BA%8C-Selector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8%EF%BC%89%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95%E4%BB%8B%E7%BB%8D"><span class="nav-text">二 Selector（选择器）的使用方法介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Selector%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="nav-text">1. Selector的创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E6%B3%A8%E5%86%8CChannel%E5%88%B0Selector"><span class="nav-text">2. 注册Channel到Selector</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F%EF%BC%9A"><span class="nav-text">注意：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-SelectionKey%E4%BB%8B%E7%BB%8D"><span class="nav-text">3. SelectionKey介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E4%BB%8ESelector%E4%B8%AD%E9%80%89%E6%8B%A9channel-Selecting-Channels-via-a-Selector"><span class="nav-text">4. 从Selector中选择channel(Selecting Channels via a Selector)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-%E5%81%9C%E6%AD%A2%E9%80%89%E6%8B%A9%E7%9A%84%E6%96%B9%E6%B3%95"><span class="nav-text">5. 停止选择的方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%89-%E6%A8%A1%E6%9D%BF%E4%BB%A3%E7%A0%81"><span class="nav-text">三 模板代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9B%9B-%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%B8%8E%E6%9C%8D%E5%8A%A1%E7%AB%AF%E7%AE%80%E5%8D%95%E4%BA%A4%E4%BA%92%E5%AE%9E%E4%BE%8B"><span class="nav-text">四 客户端与服务端简单交互实例</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">234</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">38</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">125</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/05/28/Java%20NIO%E4%B9%8BSelector%EF%BC%88%E9%80%89%E6%8B%A9%E5%99%A8)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java NIO之Selector（选择器）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-05-28 19:39:32 / 修改时间：09:08:06" itemprop="dateCreated datePublished" datetime="2021-05-28T19:39:32+08:00">2021-05-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Netty/" itemprop="url" rel="index"><span itemprop="name">Netty</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="Java-NIO之Selector（选择器）"><a href="#Java-NIO之Selector（选择器）" class="headerlink" title="Java NIO之Selector（选择器）"></a>Java NIO之Selector（选择器）</h1><blockquote>
<p>转载自<a target="_blank" rel="noopener" href="https://www.cnblogs.com/snailclimb/p/9086334.html">https://www.cnblogs.com/snailclimb/p/9086334.html</a></p>
</blockquote>
<h2 id="一-Selector（选择器）介绍"><a href="#一-Selector（选择器）介绍" class="headerlink" title="一 Selector（选择器）介绍"></a><strong>一 Selector（选择器）介绍</strong></h2><p><strong>Selector</strong> 一般称 为<strong>选择器</strong> ，当然你也可以翻译为 <strong>多路复用器</strong> 。它是Java NIO核心组件中的一个，用于检查一个或多个NIO Channel（通道）的状态是否处于可读、可写。如此可以实现单线程管理多个channels,也就是可以管理多个网络链接。</p>
<p><a target="_blank" rel="noopener" href="https://user-gold-cdn.xitu.io/2018/5/15/16363f5338f36c54?w=636&h=260&f=png&s=23373">https://user-gold-cdn.xitu.io/2018/5/15/16363f5338f36c54?w=636&amp;h=260&amp;f=png&amp;s=23373</a></p>
<p><strong>使用Selector的好处在于：</strong> 使用更少的线程来就可以来处理通道了， 相比使用多个线程，避免了线程上下文切换带来的开销。</p>
<h2 id="二-Selector（选择器）的使用方法介绍"><a href="#二-Selector（选择器）的使用方法介绍" class="headerlink" title="二 Selector（选择器）的使用方法介绍"></a><strong>二 Selector（选择器）的使用方法介绍</strong></h2><h3 id="1-Selector的创建"><a href="#1-Selector的创建" class="headerlink" title="1. Selector的创建"></a><strong>1. Selector的创建</strong></h3><p>通过调用Selector.open()方法创建一个Selector对象，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Selector selector &#x3D; Selector.open();</span><br></pre></td></tr></table></figure>

<p>这里需要说明一下</p>
<h3 id="2-注册Channel到Selector"><a href="#2-注册Channel到Selector" class="headerlink" title="2. 注册Channel到Selector"></a><strong>2. 注册Channel到Selector</strong></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">channel.configureBlocking(false);</span><br><span class="line">SelectionKey key &#x3D; channel.register(selector, Selectionkey.OP_READ);</span><br></pre></td></tr></table></figure>

<p><strong>Channel必须是非阻塞的</strong>。 所以FileChannel不适用Selector，因为FileChannel不能切换为非阻塞模式，更准确的来说是因为FileChannel没有继承SelectableChannel。Socket channel可以正常使用。</p>
<p><strong>SelectableChannel抽象类</strong> 有一个 <strong>configureBlocking（）</strong> 方法用于使通道处于阻塞模式或非阻塞模式。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">abstract SelectableChannel configureBlocking(boolean block)</span><br></pre></td></tr></table></figure>

<h3 id="注意："><a href="#注意：" class="headerlink" title="注意："></a><strong>注意：</strong></h3><p><strong>SelectableChannel抽象类</strong>的<strong>configureBlocking（）</strong> 方法是由 <strong>AbstractSelectableChannel抽象类</strong>实现的，<strong>SocketChannel、ServerSocketChannel、DatagramChannel</strong>都是直接继承了 <strong>AbstractSelectableChannel抽象类</strong> 。 </p>
<p><strong>register()</strong> 方法的第二个参数。这是一个“ <strong>interest集合</strong> ”，意思是在<strong>通过Selector监听Channel时对什么事件感兴趣</strong>。可以监听四种不同类型的事件：</p>
<ul>
<li><strong>Connect</strong></li>
<li><strong>Accept</strong></li>
<li><strong>Read</strong></li>
<li><strong>Write</strong></li>
</ul>
<p>通道触发了一个事件意思是该事件已经就绪。比如某个Channel成功连接到另一个服务器称为“ <strong>连接就绪</strong> ”。一个Server Socket Channel准备好接收新进入的连接称为“ <strong>接收就绪</strong> ”。一个有数据可读的通道可以说是“ <strong>读就绪</strong> ”。等待写数据的通道可以说是“ <strong>写就绪</strong> ”。</p>
<p>这四种事件用SelectionKey的四个常量来表示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">SelectionKey.OP_CONNECT</span><br><span class="line">SelectionKey.OP_ACCEPT</span><br><span class="line">SelectionKey.OP_READ</span><br><span class="line">SelectionKey.OP_WRITE</span><br></pre></td></tr></table></figure>

<p>如果你对不止一种事件感兴趣，使用或运算符即可，如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;</span><br></pre></td></tr></table></figure>

<h3 id="3-SelectionKey介绍"><a href="#3-SelectionKey介绍" class="headerlink" title="3. SelectionKey介绍"></a><strong>3. SelectionKey介绍</strong></h3><p>一个SelectionKey键表示了一个特定的通道对象和一个特定的选择器对象之间的注册关系。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">key.attachment(); <span class="comment">//返回SelectionKey的attachment，attachment可以在注册channel的时候指定。</span></span><br><span class="line">key.channel(); <span class="comment">// 返回该SelectionKey对应的channel。</span></span><br><span class="line">key.selector(); <span class="comment">// 返回该SelectionKey对应的Selector。</span></span><br><span class="line">key.interestOps(); <span class="comment">//返回代表需要Selector监控的IO操作的bit mask</span></span><br><span class="line">key.readyOps(); <span class="comment">// 返回一个bit mask，代表在相应channel上可以进行的IO操作。</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>key.interestOps():</p>
</blockquote>
<p>我们可以通过以下方法来判断Selector是否对Channel的某种事件感兴趣</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">int interestSet &#x3D; selectionKey.interestOps();</span><br><span class="line">boolean isInterestedInAccept &#x3D; (interestSet &amp; SelectionKey.OP_ACCEPT) &#x3D;&#x3D; SelectionKey.OP_ACCEPT；</span><br><span class="line">boolean isInterestedInConnect &#x3D; interestSet &amp; SelectionKey.OP_CONNECT;</span><br><span class="line">boolean isInterestedInRead &#x3D; interestSet &amp; SelectionKey.OP_READ;</span><br><span class="line">boolean isInterestedInWrite &#x3D; interestSet &amp; SelectionKey.OP_WRITE;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>key.readyOps()</p>
</blockquote>
<p>ready 集合是通道已经准备就绪的操作的集合。JAVA中定义以下几个方法用来检查这些操作是否就绪.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;创建ready集合的方法int readySet &#x3D; selectionKey.readyOps();</span><br><span class="line">&#x2F;&#x2F;检查这些操作是否就绪的方法</span><br><span class="line">key.isAcceptable();&#x2F;&#x2F;是否可读，是返回 trueboolean isWritable()：&#x2F;&#x2F;是否可写，是返回 trueboolean isConnectable()：&#x2F;&#x2F;是否可连接，是返回 trueboolean isAcceptable()：&#x2F;&#x2F;是否可接收，是返回 true</span><br></pre></td></tr></table></figure>

<p><strong>从SelectionKey访问Channel和Selector很简单。如下：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Channel channel &#x3D; key.channel();</span><br><span class="line">Selector selector &#x3D; key.selector();</span><br><span class="line">key.attachment();</span><br></pre></td></tr></table></figure>

<p>可以将一个对象或者更多信息附着到SelectionKey上，这样就能方便的识别某个给定的通道。例如，可以附加 与通道一起使用的Buffer，或是包含聚集数据的某个对象。使用方法如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">key.attach(theObject);</span><br><span class="line">Object attachedObj &#x3D; key.attachment();</span><br></pre></td></tr></table></figure>

<p>还可以在用register()方法向Selector注册Channel的时候附加对象。如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SelectionKey key &#x3D; channel.register(selector, SelectionKey.OP_READ, theObject);</span><br></pre></td></tr></table></figure>

<h3 id="4-从Selector中选择channel-Selecting-Channels-via-a-Selector"><a href="#4-从Selector中选择channel-Selecting-Channels-via-a-Selector" class="headerlink" title="4. 从Selector中选择channel(Selecting Channels via a Selector)"></a><strong>4. 从Selector中选择channel(Selecting Channels via a Selector)</strong></h3><p>选择器维护注册过的通道的集合，并且这种注册关系都被封装在SelectionKey当中.</p>
<blockquote>
<p>Selector维护的三种类型SelectionKey集合：</p>
</blockquote>
<ul>
<li><p><strong>已注册的键的集合(Registered key set)</strong></p>
<p>  所有与选择器关联的通道所生成的键的集合称为已经注册的键的集合。并不是所有注册过的键都仍然有效。这个集合通过 <strong>keys()</strong> 方法返回，并且可能是空的。这个已注册的键的集合不是可以直接修改的；试图这么做的话将引发java.lang.UnsupportedOperationException。</p>
</li>
<li><p><strong>已选择的键的集合(Selected key set)</strong></p>
<p>  所有与选择器关联的通道所生成的键的集合称为已经注册的键的集合。并不是所有注册过的键都仍然有效。这个集合通过 <strong>keys()</strong> 方法返回，并且可能是空的。这个已注册的键的集合不是可以直接修改的；试图这么做的话将引发java.lang.UnsupportedOperationException。</p>
</li>
<li><p><strong>已取消的键的集合(Cancelled key set)</strong></p>
<p>  已注册的键的集合的子集，这个集合包含了 <strong>cancel()</strong> 方法被调用过的键(这个键已经被无效化)，但它们还没有被注销。这个集合是选择器对象的私有成员，因而无法直接访问。</p>
<p>  <strong>注意：</strong> 当键被取消（ 可以通过<strong>isValid( )</strong> 方法来判断）时，它将被放在相关的选择器的已取消的键的集合里。注册不会立即被取消，但键会立即失效。当再次调用 <strong>select( )</strong> 方法时（或者一个正在进行的select()调用结束时），已取消的键的集合中的被取消的键将被清理掉，并且相应的注销也将完成。通道会被注销，而新的SelectionKey将被返回。当通道关闭时，所有相关的键会自动取消（记住，一个通道可以被注册到多个选择器上）。当选择器关闭时，所有被注册到该选择器的通道都将被注销，并且相关的键将立即被无效化（取消）。一旦键被无效化，调用它的与选择相关的方法就将抛出CancelledKeyException。</p>
</li>
</ul>
<blockquote>
<p>select()方法介绍：</p>
</blockquote>
<p>在刚初始化的Selector对象中，这三个集合都是空的。 <strong>通过Selector的select（）方法可以选择已经准备就绪的通道</strong> （这些通道包含你感兴趣的的事件）。比如你对读就绪的通道感兴趣，那么select（）方法就会返回读事件已经就绪的那些通道。下面是Selector几个重载的select()方法：</p>
<ul>
<li>int select()：阻塞到至少有一个通道在你注册的事件上就绪了。</li>
<li>int select(long timeout)：和select()一样，但最长阻塞时间为timeout毫秒。</li>
<li>int selectNow()：非阻塞，只要有通道就绪就立刻返回。</li>
</ul>
<p><strong>select()方法返回的int值表示有多少通道已经就绪,是自上次调用select()方法后有多少通道变成就绪状态。之前在select（）调用时进入就绪的通道不会在本次调用中被记入，而在前一次select（）调用进入就绪但现在已经不在处于就绪的通道也不会被记入</strong>。例如：首次调用select()方法，如果有一个通道变成就绪状态，返回了1，若再次调用select()方法，如果另一个通道就绪了，它会再次返回1。如果对第一个就绪的channel没有做任何操作，现在就有两个就绪的通道，但在每次select()方法调用之间，只有一个通道就绪了。</p>
<p><strong>一旦调用select()方法，并且返回值不为0时，则 可以通过调用Selector的selectedKeys()方法来访问已选择键集合</strong> 。如下：  Set selectedKeys=selector.selectedKeys();  进而可以放到和某SelectionKey关联的Selector和Channel。如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Set selectedKeys &#x3D; selector.selectedKeys();</span><br><span class="line">Iterator keyIterator &#x3D; selectedKeys.iterator();</span><br><span class="line">while(keyIterator.hasNext()) &#123;</span><br><span class="line">    SelectionKey key &#x3D; keyIterator.next();</span><br><span class="line">    if(key.isAcceptable()) &#123;</span><br><span class="line">        &#x2F;&#x2F; a connection was accepted by a ServerSocketChannel.</span><br><span class="line">    &#125; else if (key.isConnectable()) &#123;</span><br><span class="line">        &#x2F;&#x2F; a connection was established with a remote server.</span><br><span class="line">    &#125; else if (key.isReadable()) &#123;</span><br><span class="line">        &#x2F;&#x2F; a channel is ready for reading</span><br><span class="line">    &#125; else if (key.isWritable()) &#123;</span><br><span class="line">        &#x2F;&#x2F; a channel is ready for writing</span><br><span class="line">    &#125;</span><br><span class="line">    keyIterator.remove();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="5-停止选择的方法"><a href="#5-停止选择的方法" class="headerlink" title="5. 停止选择的方法"></a><strong>5. 停止选择的方法</strong></h3><p>选择器执行选择的过程，系统底层会依次询问每个通道是否已经就绪，这个过程可能会造成调用线程进入阻塞状态,那么我们有以下三种方式可以唤醒在select（）方法中阻塞的线程。</p>
<ul>
<li><strong>wakeup()方法</strong> ：通过调用Selector对象的wakeup（）方法让处在阻塞状态的select()方法立刻返回 该方法使得选择器上的第一个还没有返回的选择操作立即返回。如果当前没有进行中的选择操作，那么下一次对select()方法的一次调用将立即返回。</li>
<li><strong>close()方法</strong> ：通过close（）方法关闭Selector， 该方法使得任何一个在选择操作中阻塞的线程都被唤醒（类似wakeup（）），同时使得注册到该Selector的所有Channel被注销，所有的键将被取消，但是Channel本身并不会关闭。</li>
</ul>
<h2 id="三-模板代码"><a href="#三-模板代码" class="headerlink" title="三 模板代码"></a><strong>三 模板代码</strong></h2><p><strong>一个服务端的模板代码：</strong></p>
<p>有了模板代码我们在编写程序时，大多数时间都是在模板代码中添加相应的业务代码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">ServerSocketChannel ssc &#x3D; ServerSocketChannel.open();</span><br><span class="line">ssc.socket().bind(new InetSocketAddress(&quot;localhost&quot;, 8080));</span><br><span class="line">ssc.configureBlocking(false);</span><br><span class="line"></span><br><span class="line">Selector selector &#x3D; Selector.open();</span><br><span class="line">ssc.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line">while(true) &#123;</span><br><span class="line">    int readyNum &#x3D; selector.select();</span><br><span class="line">    if (readyNum &#x3D;&#x3D; 0) &#123;</span><br><span class="line">        continue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Set&lt;SelectionKey&gt; selectedKeys &#x3D; selector.selectedKeys();</span><br><span class="line">    Iterator&lt;SelectionKey&gt; it &#x3D; selectedKeys.iterator();</span><br><span class="line"></span><br><span class="line">    while(it.hasNext()) &#123;</span><br><span class="line">        SelectionKey key &#x3D; it.next();</span><br><span class="line"></span><br><span class="line">        if(key.isAcceptable()) &#123;</span><br><span class="line">            &#x2F;&#x2F; 接受连接</span><br><span class="line">        &#125; else if (key.isReadable()) &#123;</span><br><span class="line">            &#x2F;&#x2F; 通道可读</span><br><span class="line">        &#125; else if (key.isWritable()) &#123;</span><br><span class="line">            &#x2F;&#x2F; 通道可写</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        it.remove();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="四-客户端与服务端简单交互实例"><a href="#四-客户端与服务端简单交互实例" class="headerlink" title="四 客户端与服务端简单交互实例"></a><strong>四 客户端与服务端简单交互实例</strong></h2><p><strong>服务端：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">package selector;</span><br><span class="line"></span><br><span class="line">import java.io.IOException;</span><br><span class="line">import java.net.InetSocketAddress;</span><br><span class="line">import java.nio.ByteBuffer;</span><br><span class="line">import java.nio.channels.SelectionKey;</span><br><span class="line">import java.nio.channels.Selector;</span><br><span class="line">import java.nio.channels.ServerSocketChannel;</span><br><span class="line">import java.nio.channels.SocketChannel;</span><br><span class="line">import java.util.Iterator;</span><br><span class="line">import java.util.Set;</span><br><span class="line"></span><br><span class="line">public class WebServer &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            ServerSocketChannel ssc &#x3D; ServerSocketChannel.open();</span><br><span class="line">            ssc.socket().bind(new InetSocketAddress(&quot;127.0.0.1&quot;, 8000));</span><br><span class="line">            ssc.configureBlocking(false);</span><br><span class="line"></span><br><span class="line">            Selector selector &#x3D; Selector.open();</span><br><span class="line">            &#x2F;&#x2F; 注册 channel，并且指定感兴趣的事件是 Accept</span><br><span class="line">            ssc.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line">            ByteBuffer readBuff &#x3D; ByteBuffer.allocate(1024);</span><br><span class="line">            ByteBuffer writeBuff &#x3D; ByteBuffer.allocate(128);</span><br><span class="line">            writeBuff.put(&quot;received&quot;.getBytes());</span><br><span class="line">            writeBuff.flip();</span><br><span class="line"></span><br><span class="line">            while (true) &#123;</span><br><span class="line">                int nReady &#x3D; selector.select();</span><br><span class="line">                Set&lt;SelectionKey&gt; keys &#x3D; selector.selectedKeys();</span><br><span class="line">                Iterator&lt;SelectionKey&gt; it &#x3D; keys.iterator();</span><br><span class="line"></span><br><span class="line">                while (it.hasNext()) &#123;</span><br><span class="line">                    SelectionKey key &#x3D; it.next();</span><br><span class="line">                    it.remove();</span><br><span class="line"></span><br><span class="line">                    if (key.isAcceptable()) &#123;</span><br><span class="line">                        &#x2F;&#x2F; 创建新的连接，并且把连接注册到selector上，而且，&#x2F;&#x2F; 声明这个channel只对读操作感兴趣。</span><br><span class="line">                        SocketChannel socketChannel &#x3D; ssc.accept();</span><br><span class="line">                        socketChannel.configureBlocking(false);</span><br><span class="line">                        socketChannel.register(selector, SelectionKey.OP_READ);</span><br><span class="line">                    &#125;</span><br><span class="line">                    else if (key.isReadable()) &#123;</span><br><span class="line">                        SocketChannel socketChannel &#x3D; (SocketChannel) key.channel();</span><br><span class="line">                        readBuff.clear();</span><br><span class="line">                        socketChannel.read(readBuff);</span><br><span class="line"></span><br><span class="line">                        readBuff.flip();</span><br><span class="line">                        System.out.println(&quot;received : &quot; + new String(readBuff.array()));</span><br><span class="line">                        key.interestOps(SelectionKey.OP_WRITE);</span><br><span class="line">                    &#125;</span><br><span class="line">                    else if (key.isWritable()) &#123;</span><br><span class="line">                        writeBuff.rewind();</span><br><span class="line">                        SocketChannel socketChannel &#x3D; (SocketChannel) key.channel();</span><br><span class="line">                        socketChannel.write(writeBuff);</span><br><span class="line">                        key.interestOps(SelectionKey.OP_READ);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>客户端：</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">package selector;</span><br><span class="line"></span><br><span class="line">import java.io.IOException;</span><br><span class="line">import java.net.InetSocketAddress;</span><br><span class="line">import java.nio.ByteBuffer;</span><br><span class="line">import java.nio.channels.SocketChannel;</span><br><span class="line"></span><br><span class="line">public class WebClient &#123;</span><br><span class="line">    public static void main(String[] args) throws IOException &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            SocketChannel socketChannel &#x3D; SocketChannel.open();</span><br><span class="line">            socketChannel.connect(new InetSocketAddress(&quot;127.0.0.1&quot;, 8000));</span><br><span class="line"></span><br><span class="line">            ByteBuffer writeBuffer &#x3D; ByteBuffer.allocate(32);</span><br><span class="line">            ByteBuffer readBuffer &#x3D; ByteBuffer.allocate(32);</span><br><span class="line"></span><br><span class="line">            writeBuffer.put(&quot;hello&quot;.getBytes());</span><br><span class="line">            writeBuffer.flip();</span><br><span class="line"></span><br><span class="line">            while (true) &#123;</span><br><span class="line">                writeBuffer.rewind();</span><br><span class="line">                socketChannel.write(writeBuffer);</span><br><span class="line">                readBuffer.clear();</span><br><span class="line">                socketChannel.read(readBuffer);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>运行结果：</strong></p>
<p>先运行服务端，再运行客户端，服务端会不断收到客户端发送过来的消息。</p>
<p><a target="_blank" rel="noopener" href="https://user-gold-cdn.xitu.io/2018/5/16/1636720b53ff3a72?w=1090&h=217&f=png&s=15376">https://user-gold-cdn.xitu.io/2018/5/16/1636720b53ff3a72?w=1090&amp;h=217&amp;f=png&amp;s=15376</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/netty/" rel="tag"># netty</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/05/28/%E6%89%8B%E5%8A%A8%E6%90%AD%E5%BB%BAI%20O%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E6%A1%86%E6%9E%B61%EF%BC%9ASocket%E5%92%8CServerSocket%E5%85%A5%E9%97%A8%E5%AE%9E%E6%88%98%EF%BC%8C%E5%AE%9E%E7%8E%B0%E5%8D%95%E8%81%8A/" rel="prev" title="手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊">
                  <i class="fa fa-chevron-left"></i> 手动搭建I/O网络通信框架1：Socket和ServerSocket入门实战，实现单聊
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/06/01/%E5%A6%82%E4%BD%95%E6%AD%A3%E7%A1%AE%E7%9A%84%E4%BD%BF%E7%94%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E8%AF%BB%E5%86%99%E5%88%86%E7%A6%BB/" rel="next" title="如何正确的使用数据库读写分离">
                  如何正确的使用数据库读写分离 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
